<template>
  <div class="app-container">
    <el-row>
      <el-form :model="queryForm" inline size="small">
        <el-form-item prop="year" label="学年">
          <year-select v-model.number="queryForm.year"></year-select>
        </el-form-item>
        <el-form-item prop="semester" label="学期">
          <semester-select v-model.number="queryForm.semester"></semester-select>
        </el-form-item>
        <el-button icon="el-icon-search" size="small" type="primary" @click="onClickSearch">查询未排课课程</el-button>
      </el-form>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>课程列表</span>
          </div>
          <el-row>
            <div class="el-transfer-panel">
              <p class="el-transfer-panel__header">
                <el-row type="flex" justify="space-between" align="middle">
                  未排课课程列表
                  <el-radio-group v-model="treeType" size="mini">
                    <el-radio-button v-for="type in treeTypeList" :label="type.value">{{ type.label }}</el-radio-button>
                  </el-radio-group>
                </el-row>
              </p>
              <div class="el-transfer-panel__body">
                <div role="group" aria-label="checkbox-group" class="el-checkbox-group el-transfer-panel__list">
                  <el-input
                    placeholder="输入关键字进行过滤"
                    v-model="courseFilterText"
                    size="small">
                  </el-input>
                  <el-tree
                    ref="courseTree"
                    :data="unArrangedCourseTree"
                    show-checkbox
                    node-key="id"
                    :filter-node-method="filterNode">
                  </el-tree>
                </div>
              </div>
            </div>
          </el-row>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>定制规则</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="onClickSubmit">添加新规则</el-button>
          </div>
          <el-row>
            <el-col :span="12">
              <div class="el-transfer-panel">
                <p class="el-transfer-panel__header">
                  <el-row type="flex" justify="space-between" align="middle">
                    指定节次
                  </el-row>
                </p>
                <div class="el-transfer-panel__body">
                  <div role="group" aria-label="checkbox-group" class="el-checkbox-group el-transfer-panel__list">
                    <el-input
                      placeholder="输入关键字进行过滤"
                      v-model="sectionFilterText"
                      size="small">
                    </el-input>
                    <el-tree
                      ref="sectionTree"
                      :data="sectionList"
                      show-checkbox
                      node-key="id"
                      :filter-node-method="filterNode">
                    </el-tree>
                  </div>
                </div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="el-transfer-panel">
                <p class="el-transfer-panel__header">
                  <el-row type="flex" justify="space-between" align="middle">
                    指定教室
                  </el-row>
                </p>
                <div class="el-transfer-panel__body">
                  <div role="group" aria-label="checkbox-group" class="el-checkbox-group el-transfer-panel__list">
                    <el-input
                      placeholder="输入关键字进行过滤"
                      v-model="classroomFilterText"
                      size="small">
                    </el-input>
                    <el-tree
                      ref="classroomTree"
                      :data="classroomList"
                      show-checkbox
                      node-key="id"
                      :filter-node-method="filterNode">
                    </el-tree>
                  </div>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>
    <el-row>
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>已添加规则列表</span>
          <el-button style="float: right; padding: 3px 0" type="text" @click="onClickSubmitArrange">提交排课任务</el-button>
        </div>
        <el-table :data="courseRulesList">
          <el-table-column label="课程" prop="courseName"></el-table-column>
          <el-table-column label="节次" prop="sectionName"></el-table-column>
          <el-table-column label="教室" prop="classroomName"></el-table-column>
          <el-table-column fixed="right" label="操作" width="100">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="handleEdit(scope.$index)">编辑</el-button>
              <el-button type="text" size="small" @click="handleDelete(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-row>
  </div>
</template>

<script>
import {getUnArrangedCourseList} from "@/api/course";
import {arrange} from "@/api/schedule";
import {getAllSection} from "@/api/section";
import sectionShowMixin from "@/components/SectionShow/sectionShowMixin";
import {getClassroomTreeList} from "@/api/build";
import YearSelect from "@/components/YearSelect";
import SemesterSelect from "@/components/SemesterSelect";

export default {
  components: {SemesterSelect, YearSelect},
  mixins: [sectionShowMixin],
  data() {
    return {
      unArrangedCourseList: [],
      treeTypeList: [
        {label: '按院系分类', value: 'dept'},
        {label: '按课程分类', value: 'course'},
        {label: '按教师分类', value: 'teacher'}
      ],
      treeType: 'course',
      sectionFilterText: '',
      classroomFilterText: '',
      courseFilterText: '',
      sectionList: [],
      classroomList: [],
      courseRulesList: [],
      queryForm: {
        year: null,
        semester: null
      },
      currentYear: null,
      currentSemster: null
    }
  },
  created() {
    getAllSection().then(res => {
      const data = []
      const filter = this.$options.filters['sectionFilter']
      for (let i of res.data) {
        data.push({
          id: i.id,
          label: filter(i),
        })
      }
      this.sectionList = [
        {
          id: `all`,
          label: `全部(${data.length}条)`,
          children: data
        }
      ]
    })
    getClassroomTreeList().then(res => {
      const data = []
      for (let i of res.data) {
        data.push({
          id: `_${i.id}`,
          label: i.name,
          children: i.classrooms.map(item => {
            return {
              id: item.id,
              label: item.name
            }
          })
        })
      }
      this.classroomList = [
        {
          id: `all`,
          label: `全部(${data.length}条)`,
          children: data
        }
      ]
    })
  },
  watch: {
    classroomFilterText(val) {
      this.$refs.classroomTree.filter(val);
    },
    courseFilterText(val) {
      this.$refs.courseTree.filter(val);
    },
    sectionFilterText(val) {
      this.$refs.sectionTree.filter(val);
    }
  },
  methods: {
    filterNode(value, data) {
      if (!value || !data) return true;
      return data.label.indexOf(value) !== -1;
    },
    onClickSearch() {
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      getUnArrangedCourseList(this.queryForm.year, this.queryForm.semester).then(res => {
        this.unArrangedCourseList = res.data
        this.currentYear = this.queryForm.year
        this.currentSemster = this.queryForm.semester
        this.courseRulesList = []
        this.$message({
          type: 'success',
          message: '查询成功'
        })
      }).finally(() => {
        loading.close()
      })
    },
    onClickSubmit() {
      const classrooms = this.$refs.classroomTree.getCheckedNodes().filter(item => typeof item.id === 'number')
      const courses = this.$refs.courseTree.getCheckedNodes().filter(item => typeof item.id === 'number')
      const sections = this.$refs.sectionTree.getCheckedNodes().filter(item => typeof item.id === 'number')

      if (classrooms.length === 0) {
        this.$message({
          type: 'error',
          message: '请选择教室'
        })
        return
      }
      if (sections.length === 0) {
        this.$message({
          type: 'error',
          message: '请选择节次'
        })
        return
      }
      if (courses.length === 0) {
        this.$message({
          type: 'error',
          message: '请选择课程'
        })
        return
      }

      this.courseRulesList.push({
        courseName: courses.map(item => item.label).join('、') || '无',
        classroomName: classrooms.map(item => item.label).join('、') || '无',
        sectionName: sections.map(item => item.label).join('、') || '无',
        courses: courses.map(item => item.id),
        classrooms: classrooms.map(item => item.id),
        sections: sections.map(item => item.id)
      })

      this.$refs.classroomTree.setCheckedKeys([])
      this.$refs.courseTree.setCheckedKeys([])
      this.$refs.sectionTree.setCheckedKeys([])
    },
    handleEdit(index) {
      const curr = this.courseRulesList[index]
      this.$refs.classroomTree.setCheckedNodes(curr.classrooms)
      this.$refs.courseTree.setCheckedNodes(curr.courses)
      this.$refs.sectionTree.setCheckedNodes(curr.sections)
    },
    handleDelete(index) {
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.courseRulesList.splice(index, 1)
      })
    },
    onClickSubmitArrange() {
      if(this.courseRulesList.length === 0) {
        this.$message({
          type: 'error',
          message: '您还没有添加要排课的课程'
        })
        return
      }
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      arrange(this.currentYear, this.currentSemster, this.courseRulesList).then(res => {
        this.$message({
          type: 'success',
          message: res.msg
        })
      }).finally(() => {
        loading.close()
      })
    }
  },
  computed: {
    unArrangedCourseTree() {
      const data = []
      switch (this.treeType) {
        case 'course': {
          const indexMap = {}
          for (let i of this.unArrangedCourseList) {
            let index = indexMap[i.name]
            if (index == null) {
              index = indexMap[i.name] = data.length
              data.push({
                id: `_${index}`,
                label: i.name,
                children: []
              })
            }
            data[index].children.push({
              id: i.id,
              label: `${i.name}-${i.teacher.name}(${i.teacher.jobNumber})`
            })
          }
          break
        }
      }
      return [
        {
          id: `all`,
          label: `全部(${data.length}条)`,
          children: data
        }
      ]
    }
  }
}
</script>

<style scoped>

</style>
